import GameMgr from "./gameMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Toast extends cc.Component {
    @property
    duration: number = 0.15;
    // 定义Toast的起始位置
    outOfWorld = cc.v2(3000, 0)
    // 定义淡入动画
    actionFadeIn = null
    // 定义淡出动画
    actionFadeOut = null
    // 标题
    _title: cc.Label = null
    // 内容
    _content: cc.Label = null
    // 按钮文字
    _btn_label: cc.Label = null
    // 按钮回调函数
    _btn_callback = null

    onLoad() {
        this.node.active = false
        this.node.position.x = this.outOfWorld.x
        this.node.position.y = this.outOfWorld.y
        this.actionFadeIn = cc.tween(this.node).to(this.duration, { opacity: 255, scale: 1.0 }).call(() => {
            this.fadeInCallback()
        })
        this.actionFadeOut = cc.tween(this.node).to(this.duration, { opacity: 0, scale: 2.0 }).call(() => {
            this.fadeOutCallback()
        })
        this.node.on("fade-in", this.startFadeIn, this)
        this.node.on("fade-out", this.startFadeOut, this)
    }

    startFadeIn({ title, content, btntext, callback }) {
        this.node.active = true
        this.node.position = cc.v3(0, 0, 0)
        this.node.setScale(2.0)
        this.node.opacity = 0
        this.actionFadeIn.start()
        this.initContent(title, content, btntext)
        this._btn_callback = callback

    }

    initContent(title, content, btntext) {
        this._title = this.node.getChildByName("toast_sprite").getChildByName("title_label").getComponent(cc.Label)
        let toast_btn = this.node.getChildByName("toast_sprite").getChildByName("toast_btn")
        this._btn_label = toast_btn.getChildByName("toast_btnlabel").getComponent(cc.Label)
        let toast_layout = this.node.getChildByName("toast_sprite").getChildByName("toast_layout")
        this._content = toast_layout.getChildByName("toast_contentlabel").getComponent(cc.Label)
        this._title.string = title
        this._content.string = content
        this._btn_label.string = btntext
        GameMgr.instance.utils.addClickEvent(toast_btn, this.node, "Toast", "onClick")
    }

    onClick() {
        this.node.emit("fade-out")
    }

    startFadeOut() {
        if (typeof this._btn_callback === "function") {
            this._btn_callback()
        }
        this.actionFadeOut.start()
        this._title.string = ""
        this._content.string = ""
        this._btn_label.string = ""
        this._btn_callback = null
    }

    fadeInCallback() {

    }

    fadeOutCallback() {
        this.node.setPosition(this.outOfWorld.x, this.outOfWorld.y)
    }
}
